package com.itboye.ihomebank.activity.keytwo;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.GuanLiPassBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.util.SPUtils.get;

/**
 * 设置租户密码
 */
public class SetPassActivity extends BaseOtherActivity implements CommonCallback, Observer {
    View v_statusbar;
    ImageView close_icon;// 返回图片
    TextView add_shap_title_tv;// 标题
    EditText set_one, set_two, set_three, set_four, set_five;
    TextView update_ok;
    String lockid, lockMac;
    KeyTwoPresenter keyPresenter;
    String uid;
    long end;
    int cz;
    @Override
    protected int layout_id() {
        return R.layout.activity_set_pass;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("设置密码");
        lockid = getIntent().getStringExtra("lockid");
        lockMac = getIntent().getStringExtra("lockMac");
        end=getIntent().getLongExtra("end",0);

        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);
        uid = get(this, null, SPContants.USER_ID, "") + "";
        keyPresenter = new KeyTwoPresenter(this);
        showProgressDialog("正在获取密码列表", true);
        String sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
        cz=1;
        if ("".equals(sid)){
            keyPresenter.onPassJiLu(uid, lockid, "1", "20");

        }else {
            keyPresenter.onPassJiLu(sid, lockid, "1", "20");

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SLock.getServices().disconnectBle();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    JSONArray jsonArray = new JSONArray();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:// 返回
                finish();
                break;
            case R.id.update_ok:// 返回
                String one = set_one.getText().toString();
                String two = set_two.getText().toString();
                String three = set_three.getText().toString();
                String four = set_four.getText().toString();
                String five = set_five.getText().toString();
                if (!one.equals("")){
                    if (one.length() < 6){
                        ByAlert.alert("密码为6-9位数字");
                        return;
                    }
                }
                if (!two.equals("")){
                    if (two.length() < 6){
                        ByAlert.alert("密码为6-9位数字");
                        return;
                    }
                }
                if (!three.equals("")){
                    if (three.length() < 6){
                        ByAlert.alert("密码为6-9位数字");
                        return;
                    }
                }
                if (!four.equals("")){
                    if (four.length() < 6){
                        ByAlert.alert("密码为6-9位数字");
                        return;
                    }
                }
                if (!five.equals("")){
                    if (five.length() < 6){
                        ByAlert.alert("密码为6-9位数字");
                        return;
                    }
                }

                showProgressDialog("正在设置，请稍后......", true);
                List<String> passList = new ArrayList<>();
                passList.add(one);
                passList.add(two);
                passList.add(three);
                passList.add(four);
                passList.add(five);
                try {
                    jsonArray = new JSONArray();
                    for (int i = 0; i < passList.size(); i++) {
                        JSONObject obj1 = new JSONObject();
                        obj1.put("pwd_id", 51 + i + "");
                        obj1.put("pwd", passList.get(i));

                        jsonArray.put(obj1);
                    }

                } catch (Exception e) {
                }

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE)+5);//设置当前时间天数加五天
                long time=calendar.getTimeInMillis();//当前时间加五天
                if (end!=0){
                    if (end*1000<time){//如果结束时间小于当前时间加五天，就传结束时间。反之就传当前时间加五天（租客密码有五天的有效期）
                        SLock.getServices().setRentMode(lockMac, end*1000, passList);
                    }else{
                        SLock.getServices().setRentMode(lockMac, time, passList);
                    }
                }else{
                    SLock.getServices().setRentMode(lockMac, time, passList);
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onSuccess(ResultData resultData) {
        // log(resultData.getId(), false, resultData.getData());
        if (resultData.getId() == ID.SET_RENT_MODE) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //   ByAlert.alert("设置成功");
                    String sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                    cz=2;
                    if ("".equals(sid)){
                        keyPresenter.onAddPass(uid, lockid, jsonArray.toString(), TimesUtils.getStamp(), "", "", "");

                    }else {
                        keyPresenter.onAddPass(sid, lockid, jsonArray.toString(), TimesUtils.getStamp(), "", "", "");

                    }
                }
            });
        }
    }

    @Override
    public void onFailed(ResultError resultError) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
        log(resultError.getId(), false, resultError.getErrorCode().toLog());

    }

    private void log(final ID id, final boolean isSuccess, final String log) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isSuccess) {
                    ByAlert.alert(log);
                } else {
                    ByAlert.alert(TostKey.getStamp(log));
                }
            }
        });

    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getEventType() == keyPresenter.pass_jilu_success) {
                GuanLiPassBean bean = (GuanLiPassBean) entity.getData();
             //   ByAlert.alert(entity.getData());
                List<GuanLiPassBean.Date> listBean=new ArrayList<>();
                if (bean!=null){
                    listBean.addAll(bean.getData());
                    if (listBean.size()==5){//获取到五组之前设置的密码，显示在五个输入框内
                        set_one.setText(listBean.get(0).getKeyboard_pwd());
                        set_two.setText(listBean.get(1).getKeyboard_pwd());
                        set_three.setText(listBean.get(2).getKeyboard_pwd());
                        set_four.setText(listBean.get(3).getKeyboard_pwd());
                        set_five.setText(listBean.get(4).getKeyboard_pwd());
                    }
                }

            } else if (entity.getEventType() == keyPresenter.pass_jilu_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            } else if (entity.getEventType() == keyPresenter.add_pass_success) {
                ByAlert.alert(entity.getData());

            } else if (entity.getEventType() == keyPresenter.add_pass_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            }else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData(data1.getSid());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private void toRefreshData(String sid) {
        if (cz==1){

            if ("".equals(sid)){
                keyPresenter.onPassJiLu(uid, lockid, "1", "20");

            }else {
                keyPresenter.onPassJiLu(sid, lockid, "1", "20");

            }
        }else if (cz==2){

            if ("".equals(sid)){
                keyPresenter.onAddPass(uid, lockid, jsonArray.toString(), TimesUtils.getStamp(), "", "", "");

            }else {
                keyPresenter.onAddPass(sid, lockid, jsonArray.toString(), TimesUtils.getStamp(), "", "", "");

            }
        }

    }
}
